import React, { useState } from "react";

const UserList = () => {
  const [users, setUsers] = useState([
    { id: 1, name: "Alice", account: "alice123", health: "Good", age: 28 },
    { id: 2, name: "Bob", account: "bob456", health: "Fair", age: 35 },
    { id: 3, name: "Charlie", account: "charlie789", health: "Excellent", age: 22 },
  ]);
  const [editingUserId, setEditingUserId] = useState(null);
  const [formData, setFormData] = useState({ health: "", age: "" });

  // Handle editing
  const startEditing = (user) => {
    setEditingUserId(user.id);
    setFormData({ health: user.health, age: user.age });
  };

  const cancelEditing = () => {
    setEditingUserId(null);
    setFormData({ health: "", age: "" });
  };

  const saveChanges = (id) => {
    setUsers((prevUsers) =>
      prevUsers.map((user) =>
        user.id === id ? { ...user, health: formData.health, age: formData.age } : user
      )
    );
    setEditingUserId(null);
  };

  // Handle deletion
  const deleteUser = async (id) => {
    try {
      // Simulating a network request
      const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`, {
        method: "DELETE",
      });
      if (response.ok) {
        setUsers((prevUsers) => prevUsers.filter((user) => user.id !== id));
        alert("User deleted successfully");
      } else {
        alert("Failed to delete user");
      }
    } catch (error) {
      console.error("Error deleting user:", error);
    }
  };

  return (
    <div style={{ padding: "20px", fontFamily: "Arial" }}>
      <h1>User List</h1>
      <table border="1" style={{ width: "100%", borderCollapse: "collapse" }}>
        <thead>
          <tr>
            <th>Name</th>
            <th>Account</th>
            <th>Health</th>
            <th>Age</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {users.map((user) => (
            <tr key={user.id}>
              <td>{user.name}</td>
              <td>{user.account}</td>
              <td>
                {editingUserId === user.id ? (
                  <input
                    type="text"
                    value={formData.health}
                    onChange={(e) => setFormData({ ...formData, health: e.target.value })}
                  />
                ) : (
                  user.health
                )}
              </td>
              <td>
                {editingUserId === user.id ? (
                  <input
                    type="number"
                    value={formData.age}
                    onChange={(e) => setFormData({ ...formData, age: e.target.value })}
                  />
                ) : (
                  user.age
                )}
              </td>
              <td>
                {editingUserId === user.id ? (
                  <>
                    <button onClick={() => saveChanges(user.id)}>Save</button>
                    <button onClick={cancelEditing}>Cancel</button>
                  </>
                ) : (
                  <>
                    <button onClick={() => startEditing(user)}>Edit</button>
                    <button onClick={() => deleteUser(user.id)}>Delete</button>
                  </>
                )}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      {users.length === 0 && <p>No users available!</p>}
    </div>
  );
};

export default UserList;